package Modelo.Util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Grisel
 */
public class AdministradorDeSesiones {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // load from different directory
            SessionFactory sessionF = new Configuration().configure(
                    "Modelo/xml/hibernate.cfg.xml").buildSessionFactory();

            return sessionF;

        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    //public static void shutdown() {
    // Close caches and connection pools
    //	getSessionFactory().close();
    //}
    public static Session beginTransaction() {
        Session hibernateSession = AdministradorDeSesiones.getSession();
        hibernateSession.beginTransaction();
        return hibernateSession;
    }

    public static void commitTransaction() {
        AdministradorDeSesiones.getSession().getTransaction().commit();
    }

    public static void rollbackTransaction() {
        AdministradorDeSesiones.getSession().getTransaction().rollback();
    }

    public static void closeSession() {
        AdministradorDeSesiones.getSession().close();
    }

    public static Session getSession() {
        Session hibernateSession = sessionFactory.getCurrentSession();
        return hibernateSession;
    }
}